/* 
** (Copyright) sejishikong <sejishikong@263.net>
** Authors:    sejishikong <sejishikong@263.net>
**             Wei Lian <lianwei2003.student@sina.com> 
** Maintainer: Wei Lian
**    This program is free software; you can redistribute it and/or modify
**    it under the terms of the GNU General Public License Version 2 as
**    published by the Free Software Foundation;
**
**    This program is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**    GNU General Public License for more details.
**
**    You should have received a copy of the GNU General Public License
**    along with this program; if not, write to the Free Software
**    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
*/

#include "sopcast.h"
#include "sys.h"
#include "config.h"

////fork new process
bool Sopcast::forksop (QString url)
{
  int
    i;
  char
    inport[8];
  int
    sock;
  ///choose inport and outport number
  for (i = 8000; i < 9000; i++)
    {
      sock = sys->connect_to_server ("127.0.0.1", i);
      if (sock == -1)
	break;
      else if (sock >= 0)
	::close (sock);
    }
  sprintf (inport, "%d", i);
  vboxconfig->labelinport->setText (inport);

  for (i = 9000; i < 10000; i++)
    {
      sock = sys->connect_to_server ("127.0.0.1", i);
      if (sock == -1)
	break;
      else if (sock >= 0)
	::close (sock);
    }
  sprintf (outport, "%d", i);
  vboxconfig->labeloutport->setText (outport);
  ////    
  sop->clearArguments ();
  sop->addArgument ("sp-sc");
  sop->addArgument (url);
  sop->addArgument (inport);
  sop->addArgument (outport);
  return sop->start ();
}

bool Sopcast::forkplayer ()
{
  player->clearArguments ();
  QStringList
    strlst = QStringList::split (" ", vboxconfig->editplayer->text ());
  for (QStringList::Iterator it = strlst.begin (); it != strlst.end (); ++it)
    {
      player->addArgument (*it);
    }

  QString
    url = "http://localhost:";
  url += outport;
  player->addArgument (url);
  return player->start ();
}

////kill process
void
Sopcast::killsop ()
{
  flaghook = FALSE;
  if (sop->isRunning ())
    {
//      sop->tryTerminate ();
      sop->kill ();
    }
}

void
Sopcast::killplayer ()
{
  if (player->isRunning ())
    {
      player->tryTerminate ();
//      QTimer::singleShot (500, player, SLOT (kill ()));
    }

}
